"use client"

import { useState, useEffect } from "react"
import {
  Table,
  Card,
  Button,
  Input,
  Space,
  Tag,
  Modal,
  Form,
  Select,
  DatePicker,
  Row,
  Col,
  message,
  Popconfirm,
  Typography,
  Tabs,
  Descriptions,
  Timeline,
  Steps,
  Divider,
} from "antd"
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  ClockCircleOutlined,
  AppstoreOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
} from "@ant-design/icons"
// 添加以下导入
import {
  getEvents,
  addEvent,
  updateEvent,
  deleteEvent,
} from "@/utils/api/event"
import { getCustomers } from "@/utils/api/customer"
import dayjs from "dayjs"

const { Title } = Typography
const { Option } = Select
const { TabPane } = Tabs

const EventManagement = () => {
  const [loading, setLoading] = useState(false)
  const [events, setEvents] = useState([])
  const [customers, setCustomers] = useState([])
  const [eventModalVisible, setEventModalVisible] = useState(false)
  const [eventDetailsVisible, setEventDetailsVisible] = useState(false)
  const [modalTitle, setModalTitle] = useState("添加婚礼活动")
  const [selectedEvent, setSelectedEvent] = useState(null)
  const [searchText, setSearchText] = useState("")
  const [form] = Form.useForm()

  // 获取婚礼活动列表和客户列表
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        const [eventsResponse, customersResponse] = await Promise.all([
          getEvents(), // 替换为api函数
          getCustomers(), // 替换为api函数
        ])

        setEvents(eventsResponse)
        setCustomers(customersResponse)
      } catch (error) {
        console.error("获取数据错误:", error)
        message.error("获取数据失败")
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  // 搜索过滤
  const filteredEvents = events.filter(
    (event) =>
      event.name.toLowerCase().includes(searchText.toLowerCase()) ||
      event.customer.toLowerCase().includes(searchText.toLowerCase()) ||
      event.venue.toLowerCase().includes(searchText.toLowerCase())
  )

  // 添加或更新婚礼活动
  const handleSaveEvent = async () => {
    try {
      const values = await form.validateFields()

      if (selectedEvent) {
        // 更新活动
        await updateEvent(selectedEvent.id, values) // 替换为api函数
        message.success("婚礼活动更新成功")
      } else {
        // 添加活动
        await addEvent(values) // 替换为api函数
        message.success("婚礼活动添加成功")
      }

      setEventModalVisible(false)
      form.resetFields()
      // 重新获取活动列表
      const response = await getEvents() // 替换为api函数
      setEvents(response)
    } catch (error) {
      console.error("保存婚礼活动错误:", error)
      message.error("操作失败，请稍后重试")
    }
  }

  // 删除婚礼活动
  const handleDeleteEvent = async (id) => {
    try {
      await deleteEvent(id) // 替换为api函数
      message.success("婚礼活动删除成功")
      // 重新获取活动列表
      const response = await getEvents() // 替换为api函数
      setEvents(response)
    } catch (error) {
      console.error("删除婚礼活动错误:", error)
      message.error("删除失败，请稍后重试")
    }
  }

  // 打开编辑模态框
  const handleEditEvent = (event) => {
    setSelectedEvent(event)
    setModalTitle("编辑婚礼活动")
    form.setFieldsValue({
      ...event,
      date: event.date ? dayjs(event.date) : null,
      time: event.time ? dayjs(event.time, "HH:mm") : null,
    })
    setEventModalVisible(true)
  }

  // 打开添加模态框
  const handleAddEvent = () => {
    setSelectedEvent(null)
    setModalTitle("添加婚礼活动")
    form.resetFields()
    setEventModalVisible(true)
  }

  // 查看婚礼详情
  const handleViewEventDetails = (event) => {
    setSelectedEvent(event)
    setEventDetailsVisible(true)
  }

  // 获取婚礼状态的显示标签
  const getStatusTag = (status) => {
    let color = "default"
    let text = "未知"

    switch (status) {
      case "pending":
        color = "gold"
        text = "待确认"
        break
      case "confirmed":
        color = "green"
        text = "已确认"
        break
      case "completed":
        color = "blue"
        text = "已完成"
        break
      case "canceled":
        color = "red"
        text = "已取消"
        break
      default:
        color = "default"
        text = status
    }

    return <Tag color={color}>{text}</Tag>
  }

  // 获取进度状态
  const getProgressStatus = (status) => {
    switch (status) {
      case "pending":
        return 0
      case "confirmed":
        return 1
      case "inProgress":
        return 2
      case "completed":
        return 3
      case "canceled":
        return 4
      default:
        return 0
    }
  }

  const columns = [
    {
      title: "婚礼名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "客户",
      dataIndex: "customer",
      key: "customer",
    },
    {
      title: "日期",
      dataIndex: "date",
      key: "date",
    },
    {
      title: "时间",
      dataIndex: "time",
      key: "time",
    },
    {
      title: "地点",
      dataIndex: "venue",
      key: "venue",
    },
    {
      title: "预算(万元)",
      dataIndex: "budget",
      key: "budget",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => getStatusTag(status),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => handleViewEventDetails(record)}
          />
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEditEvent(record)}
          />
          <Popconfirm
            title="确定要删除此婚礼活动吗?"
            description="此操作不可撤销!"
            onConfirm={() => handleDeleteEvent(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div className="event-management">
      <div className="page-header">
        <Title level={4} className="page-title">
          婚礼活动管理
        </Title>
      </div>

      <Card>
        <div className="table-operations">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAddEvent}
          >
            添加婚礼活动
          </Button>
          <div className="table-search">
            <Input
              placeholder="搜索婚礼名称、客户或地点"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 300 }}
              allowClear
            />
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={filteredEvents}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 添加/编辑婚礼活动模态框 */}
      <Modal
        title={modalTitle}
        open={eventModalVisible}
        onCancel={() => setEventModalVisible(false)}
        onOk={handleSaveEvent}
        width={720}
        okText="保存"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="婚礼名称"
                rules={[{ required: true, message: "请输入婚礼名称" }]}
              >
                <Input placeholder="请输入婚礼名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="customerId"
                label="客户"
                rules={[{ required: true, message: "请选择客户" }]}
              >
                <Select placeholder="请选择客户">
                  {customers.map((customer) => (
                    <Option key={customer.id} value={customer.id}>
                      {customer.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="date"
                label="日期"
                rules={[{ required: true, message: "请选择日期" }]}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  placeholder="请选择日期"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="time"
                label="时间"
                rules={[{ required: true, message: "请选择时间" }]}
              >
                <DatePicker.TimePicker
                  style={{ width: "100%" }}
                  placeholder="请选择时间"
                  format="HH:mm"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="venue"
                label="地点"
                rules={[{ required: true, message: "请输入地点" }]}
              >
                <Input placeholder="请输入地点" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="budget"
                label="预算(万元)"
                rules={[{ required: true, message: "请输入预算" }]}
              >
                <Input type="number" placeholder="请输入预算" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: "请选择状态" }]}
              >
                <Select placeholder="请选择状态">
                  <Option value="pending">待确认</Option>
                  <Option value="confirmed">已确认</Option>
                  <Option value="inProgress">进行中</Option>
                  <Option value="completed">已完成</Option>
                  <Option value="canceled">已取消</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="type"
                label="婚礼类型"
                rules={[{ required: true, message: "请选择婚礼类型" }]}
              >
                <Select placeholder="请选择婚礼类型">
                  <Option value="standard">标准婚礼</Option>
                  <Option value="luxury">豪华婚礼</Option>
                  <Option value="simple">简约婚礼</Option>
                  <Option value="theme">主题婚礼</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="description" label="活动描述">
            <Input.TextArea rows={4} placeholder="请输入活动描述" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 婚礼活动详情模态框 */}
      <Modal
        title="婚礼活动详情"
        open={eventDetailsVisible}
        onCancel={() => setEventDetailsVisible(false)}
        footer={[
          <Button key="close" onClick={() => setEventDetailsVisible(false)}>
            关闭
          </Button>,
          <Button
            key="edit"
            type="primary"
            onClick={() => {
              setEventDetailsVisible(false)
              handleEditEvent(selectedEvent)
            }}
          >
            编辑
          </Button>,
        ]}
        width={800}
      >
        {selectedEvent && (
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本信息" key="1">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="婚礼名称" span={2}>
                  {selectedEvent.name}
                </Descriptions.Item>
                <Descriptions.Item label="客户">
                  {selectedEvent.customer}
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  {getStatusTag(selectedEvent.status)}
                </Descriptions.Item>
                <Descriptions.Item label="日期">
                  {selectedEvent.date}
                </Descriptions.Item>
                <Descriptions.Item label="时间">
                  {selectedEvent.time}
                </Descriptions.Item>
                <Descriptions.Item label="地点" span={2}>
                  {selectedEvent.venue}
                </Descriptions.Item>
                <Descriptions.Item label="预算" span={2}>
                  {selectedEvent.budget} 万元
                </Descriptions.Item>
                <Descriptions.Item label="婚礼类型" span={2}>
                  {(() => {
                    switch (selectedEvent.type) {
                      case "standard":
                        return "标准婚礼"
                      case "luxury":
                        return "豪华婚礼"
                      case "simple":
                        return "简约婚礼"
                      case "theme":
                        return "主题婚礼"
                      default:
                        return selectedEvent.type
                    }
                  })()}
                </Descriptions.Item>
                <Descriptions.Item label="描述" span={2}>
                  {selectedEvent.description}
                </Descriptions.Item>
              </Descriptions>

              <Divider>进度状态</Divider>
              <Steps
                current={getProgressStatus(selectedEvent.status)}
                items={[
                  {
                    title: "待确认",
                    description: "婚礼计划待确认",
                    icon: <ClockCircleOutlined />,
                  },
                  {
                    title: "已确认",
                    description: "婚礼计划已确认",
                    icon: <CheckCircleOutlined />,
                  },
                  {
                    title: "进行中",
                    description: "婚礼准备进行中",
                    icon: <AppstoreOutlined />,
                  },
                  {
                    title: "已完成",
                    description: "婚礼已顺利完成",
                    icon: <CheckCircleOutlined />,
                  },
                  {
                    title: "已取消",
                    description: "婚礼已取消",
                    status:
                      selectedEvent.status === "canceled" ? "error" : "wait",
                    icon: <CloseCircleOutlined />,
                  },
                ]}
              />
            </TabPane>

            <TabPane tab="任务清单" key="2">
              <Timeline mode="left">
                <Timeline.Item color="green">
                  <p>确认婚礼日期和场地预订</p>
                  <p className="text-muted">需在婚礼前6个月完成</p>
                </Timeline.Item>
                <Timeline.Item color="green">
                  <p>确定婚礼预算</p>
                  <p className="text-muted">需在婚礼前5个月完成</p>
                </Timeline.Item>
                <Timeline.Item color="blue">
                  <p>选择宾客名单</p>
                  <p className="text-muted">需在婚礼前4个月完成</p>
                </Timeline.Item>
                <Timeline.Item color="blue">
                  <p>预订酒席和餐饮服务</p>
                  <p className="text-muted">需在婚礼前3个月完成</p>
                </Timeline.Item>
                <Timeline.Item color="gray">
                  <p>预订花艺和装饰</p>
                  <p className="text-muted">需在婚礼前3个月完成</p>
                </Timeline.Item>
                <Timeline.Item color="gray">
                  <p>安排摄影和摄像服务</p>
                  <p className="text-muted">需在婚礼前2个月完成</p>
                </Timeline.Item>
                <Timeline.Item color="gray">
                  <p>确认婚礼流程</p>
                  <p className="text-muted">需在婚礼前1个月完成</p>
                </Timeline.Item>
              </Timeline>
            </TabPane>

            <TabPane tab="费用明细" key="3">
              <Table
                dataSource={[
                  { id: 1, item: "场地租赁", price: "3.5万元", status: "paid" },
                  { id: 2, item: "餐饮服务", price: "4.2万元", status: "paid" },
                  {
                    id: 3,
                    item: "花艺装饰",
                    price: "1.8万元",
                    status: "unpaid",
                  },
                  {
                    id: 4,
                    item: "摄影摄像",
                    price: "1.5万元",
                    status: "unpaid",
                  },
                  {
                    id: 5,
                    item: "音响设备",
                    price: "0.8万元",
                    status: "unpaid",
                  },
                ]}
                columns={[
                  { title: "项目", dataIndex: "item", key: "item" },
                  { title: "金额", dataIndex: "price", key: "price" },
                  {
                    title: "状态",
                    dataIndex: "status",
                    key: "status",
                    render: (status) =>
                      status === "paid" ? (
                        <Tag color="green">已支付</Tag>
                      ) : (
                        <Tag color="orange">未支付</Tag>
                      ),
                  },
                ]}
                pagination={false}
                rowKey="id"
              />
              <div style={{ textAlign: "right", marginTop: 16 }}>
                <Space>
                  <span>总预算: {selectedEvent.budget} 万元</span>
                  <Divider type="vertical" />
                  <span>已支付: 7.7 万元</span>
                  <Divider type="vertical" />
                  <span>剩余: 4.1 万元</span>
                </Space>
              </div>
            </TabPane>
          </Tabs>
        )}
      </Modal>
    </div>
  )
}

export default EventManagement
